package com.inter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.OrderPaymentManager;
import com.inter.entity.newpojo.Constant;
import com.inter.entity.newrequest.aheadfinish.request.RequestAheadFinishNew;
import com.inter.entity.newrequest.aheadfinish.response.ResponseAheadFinishNew;
import com.inter.entity.newrequest.purchaseplan.request.PurchasePlanRequest;
import com.inter.entity.newrequest.purchaseplan.response.PurchasePlanResponse;
import com.inter.entity.newrequest.querypackage.request.RequestPackageQueryNew;
import com.inter.entity.newrequest.querypackage.response.ResponsePackageQueryNew;
import com.inter.mapper.AsyncOrderPlanMapper;
import com.inter.service.OrderPaymentManagerService;
import com.inter.utils.HttpUtil;
import com.inter.utils.mail.SendMailUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.annotation.Resource;

/**
 * 异步的订购套餐的逻辑梳理公共类：
 * <p>
 * 1，订购套餐之前先查询下设备上是否有正在使用的订单
 * 2，有正在使用的订单的话一定要先提前结束正在使用的订单
 * 3，订购套餐，就是发起一次下新单的请求。
 * 4，等到结果回来再返回。
 *
 * @author lm
 * @date 2020/3/25
 */

@Service("asyncOrderService")
@Transactional(rollbackFor = Exception.class)
public class AsyncOrderPlanService {

    private static Logger logger = Logger.getLogger(AsyncOrderPlanService.class);

    @Autowired
    OrderPaymentManagerService orderService;

    @Resource
    AsyncOrderPlanMapper orderPlanMapper;

    @Autowired
    JavaMailSenderImpl javaMailSender;

    /***
     * 将下单请求入库
     * @param partnerCode
     * @param partnerName
     * @param packageCode
     * @param packageName
     * @param deviceId
     * @param packageType
     * @param orderPeriod
     * @param amount
     * @param currency
     * @param requestOrderId
     * @return
     */
    public Integer storageOrderPayment(String partnerCode, String partnerName, String packageCode, String packageName, String packageType,
                                       String deviceId, String orderPeriod, String amount, String currency, String requestOrderId) {
        OrderPaymentManager userOrder = new OrderPaymentManager();
        userOrder.setPartnerCode(partnerCode);
        userOrder.setPartnerName(partnerName);
        userOrder.setPackageCode(packageCode);
        userOrder.setPackageName(packageName);
        userOrder.setDeviceId(deviceId);
        userOrder.setDeviceType("4");
        userOrder.setPackageType(packageType);
        userOrder.setOrderPeriod(orderPeriod);
        userOrder.setAmount(amount);
        userOrder.setOrderCurrency(currency);
        userOrder.setRequestOrderId(requestOrderId);
        userOrder.setIsOpen("0");
        userOrder.setGlobalOrder("0");
        userOrder.setPayRst("success");
        userOrder.setPayType("5");
        return orderPlanMapper.storageOrderPayment(userOrder);
    }

    /**
     * 查询某企业下面的设备的订单
     *
     * @param deviceId
     * @param partnerCode
     * @param secret
     * @param orderId
     * @param orderStatus
     * @param orderType
     * @return
     */
    public ResponsePackageQueryNew QueryOrder(String deviceId, String partnerCode, String secret, String orderId, String orderStatus, String orderType) {

        RequestPackageQueryNew query = new RequestPackageQueryNew();
        query.setDeviceId(deviceId);
        query.setOrderId(orderId);
        query.setOrderStatus(orderStatus);
        query.setOrderType(orderType);
        query.setPartnerCode(partnerCode);
        query.setSecret(secret);

        if ("2".equals(orderStatus)) {
            //查询有没有正在使用的订单
            String re = JSON.toJSONString(query);
            logger.info("【订购套餐】查询【正在使用】订单请求：" + re);

            String reUrl = Constant.requestURI + Constant.iot_queryOrder;
            // 发送post请求，并接收返回结果
            String reStr = HttpUtil.httpPost(reUrl, re);
            logger.info("url=" + reUrl + ";接口名：" + Constant.iot_queryOrder);

            logger.info("【订购套餐】查询【正在使用】订单响应：" + reStr);
            ResponsePackageQueryNew queryNew = JSONArray.parseObject(reStr, ResponsePackageQueryNew.class);

            return queryNew;

        } else {

            //其他未标明状态的套餐查询请求
            RequestPackageQueryNew que = new RequestPackageQueryNew();
            que.setDeviceId(deviceId);
            que.setOrderId(orderId);
            que.setOrderStatus(orderStatus);
            que.setOrderType(orderType);
            que.setPartnerCode(partnerCode);
            que.setSecret(secret);

            String r = JSON.toJSONString(que);
            logger.info("查询订单请求：" + r);
            String reUrl = Constant.requestURI + Constant.iot_queryOrder;
            // 发送post请求，并接收返回结果
            String reStr = HttpUtil.httpPost(reUrl, r);
            logger.info("url=" + reUrl + ";接口名：" + Constant.iot_queryOrder);

            logger.info("查询订单响应：" + reStr);
            ResponsePackageQueryNew quer = JSONArray.parseObject(reStr, ResponsePackageQueryNew.class);
            return quer;

        }


    }

    /**
     * 提前结束正在使用的订单
     *
     * @param partnerCode
     * @param secret
     * @param orderId
     * @param deviceType
     * @param cause
     * @return
     */
    public ResponseAheadFinishNew aheadFinishOrder(String partnerCode, String secret, String orderId, String deviceType, String cause) {

        RequestAheadFinishNew aheadFinish = new RequestAheadFinishNew();
        aheadFinish.setOrderId(orderId);
        aheadFinish.setDeviceType(deviceType);
        aheadFinish.setAheadFinishCause("流量耗尽周期未到需开启新的订单");
        aheadFinish.setPartnerCode(partnerCode);
        aheadFinish.setSecret(secret);

        //组装需要的json去请求报文
        String requestInterface = JSON.toJSONString(aheadFinish);
        logger.info("【提前结束正在使用订单】请求：" + requestInterface);
        String url = Constant.requestURI + Constant.iot_aheadFinishDeviceOrder;

        // 发送post请求，并接收返回结果
        String returnStr = HttpUtil.httpPost(url, requestInterface);
        logger.info("【提前结束正在使用订单】响应：" + returnStr);
        return JSONArray.parseObject(returnStr, ResponseAheadFinishNew.class);


    }

    /***
     * 异步的订购套餐方法
     * @param secret
     * @param partnerCode
     * @param deviceId
     * @param packageCode
     * @param packageName
     * @param packageType
     * @param orderPeriod
     * @param amount
     * @param payType
     * @return
     */
    public PurchasePlanResponse Order(String secret, String partnerCode, String deviceId, String packageCode, String packageName, String packageType, String orderPeriod, String amount, String payType) {

        PurchasePlanRequest o = new PurchasePlanRequest();
        o.setDeviceId(deviceId);
        o.setPackageName(packageName);
        o.setPackageCode(packageCode);
        o.setPackageType(packageType);
        o.setOrderPeriod(orderPeriod);
        o.setAmount(amount);
        o.setPayRst("2");
        o.setPayType(payType);
        o.setIsOpen("0");
        o.setGlobalOrder("0");
        o.setTestFlowFlag("0");
        o.setSecret(secret);
        o.setPartnerCode(partnerCode);

        String requestOrder = JSON.toJSONString(o);
        logger.info("【订购套餐】请求：" + requestOrder);
        //正式地址
        String requestOrderUrl = Constant.requestURI + Constant.iot_PurchasePlan;

        // 发送post请求，并接收返回结果
        String requestOrderReturnStr = HttpUtil.httpPost(requestOrderUrl, requestOrder);
        logger.info("url=" + requestOrderUrl + ";接口名：" + Constant.iot_PurchasePlan);

        logger.info("【订购套餐】响应：" + requestOrderReturnStr);
        return JSONArray.parseObject(requestOrderReturnStr, PurchasePlanResponse.class);

    }

    /**
     * 订购套餐回来更新订单号到数据库
     *
     * @param orderId
     * @param deviceId
     * @param partnerCode
     * @param packageCode
     * @param requestOrderId
     * @return
     */
    public Integer updateOrderId(String orderId, String deviceId, String partnerCode, String packageCode, String requestOrderId) {
        OrderPaymentManager userOrder = new OrderPaymentManager();
        userOrder.setOrderId(orderId);
        userOrder.setPartnerCode(partnerCode);
        userOrder.setPackageCode(packageCode);
        userOrder.setDeviceId(deviceId);
        userOrder.setRequestOrderId(requestOrderId);
        return orderPlanMapper.updateOrderId(userOrder);
    }

    /***
     * 发送异常邮件方法
     * @param deviceId
     * @param packageName
     * @param orderId
     * @param type
     * @param message
     */
    public void SendMail(String deviceId, String packageName, String orderId, String type, String message) {
        try {
            String sendText = "卡片ICCID:" + deviceId + "\n" +
                    "套餐名称:" + packageName + "\n" +
                    "订单编码:" + orderId + "\n" +
                    "操作类型:" + type + "\n" +
                    "异常描述:" + message + "\n";
            javaMailSender.send(new SendMailUtil().sendIdentifyingCode("Travis异步订购套餐异常处理", sendText));
            logger.info(orderId + ":异常邮件发送成功");

        } catch (MailException e) {
            logger.info("邮件发送出现异常：" + e);
        }
    }
}
